﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Lib.CommonForm.ServiceWCF;
using System.ServiceModel;

using System.Data;
using System.Security.AccessControl;
using System.IO;
using System.Security.Principal;
using Lib.CommonForm;

namespace AUI
{
    public partial class frmLogin : FormBase
    {
        string uri = "";
        string userName = "";
        string passWord = "";
        string HashPassword = "";

        public frmLogin()
        {
            InitializeComponent();

            this.Text = Globals.assemblyDescription;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Owner = Program.m_frmMain;

            cboAddress.Items.Clear();

            //Read Settings
            ConnectLog rs = new ConnectLog();
            //
            if (Globals.ToString(rs.ServiceAddressLog).Length > 0)
            {
                //Tách chuỗi sau dấu phẩy
                string[] Arg = Globals.ToString(rs.ServiceAddressLog).Split(',');

                //Gán các item vào combobox có sắp xếp
                Array.Sort<string>(Arg);
                for (int i = 0; i < Arg.Length; i++)
                {
                    cboAddress.Items.Add(Arg[i]);
                }
            }
            cboAddress.Text = rs.ServiceAddress;
            txtUserName.Text = rs.LastUser;
            txtUserPassword.Text = "1234567";

            if (!String.IsNullOrEmpty(txtUserName.Text))
                txtUserPassword.Focus();
            else
                txtUserName.Focus();

            this.Activate();
        }

        public string ProcessorId { get; set; }

        private bool CheckValid()
        {
            userName = txtUserName.Text.Trim();
            passWord = txtUserPassword.Text.Trim();
            uri = cboAddress.Text;

            txtUserName.BackColor = SystemColors.Window;
            txtUserPassword.BackColor = SystemColors.Window;
            cboAddress.BackColor = SystemColors.Window;

            if (String.IsNullOrEmpty(uri))
            {
                cboAddress.BackColor = Color.Yellow;
                FormGlobals.Message_Warning("The address can not be empty");
                cboAddress.Focus();
                return false;
            }
            if (String.IsNullOrEmpty(userName))
            {
                txtUserName.BackColor = Color.Yellow;
                FormGlobals.Message_Warning("The username can not be empty");
                txtUserName.Focus();
                return false;
            }
            if (String.IsNullOrEmpty(passWord))
            {
                txtUserPassword.BackColor = Color.Yellow;
                FormGlobals.Message_Warning("The password can not be empty");
                txtUserPassword.Focus();
                return false;
            }

            HashPassword = Globals.HashPassword(passWord);
            ServiceClient wcf = new ServiceClient(ProxyConfig.GetBinding(uri, true), new EndpointAddress(uri));
            wcf.ClientCredentials.UserName.UserName = userName;
            wcf.ClientCredentials.UserName.Password = HashPassword;

            DataTable dt = wcf.aspnet_Users_GetInfo(userName).Tables[0];

            if (Globals.ToBoolean(dt.Rows[0]["IsAnonymous"]))
            {
                FormGlobals.Message_Error(new Exception("Login failed. The reason this account has been locked."));
                return false;
            }
            wcf.Close();

            //Set parameter
            FormGlobals.strUserName = userName;
            FormGlobals.strPassword = HashPassword;
            FormGlobals.isAdmin = Globals.ToBoolean(dt.Rows[0]["isAdmin"]);
            FormGlobals.viewAllBranch = Globals.ToBoolean(dt.Rows[0]["viewAllBranch"]);
            FormGlobals.viewAllCompany = Globals.ToBoolean(dt.Rows[0]["viewAllCompany"]);

            //Write Settings

            ConnectLog c = new ConnectLog();
            string ServiceAddressLog = c.ServiceAddressLog;

            if (!ServiceAddressLog.ToLower().Contains(uri.ToLower()))
                if (!ServiceAddressLog.Contains(",") && ServiceAddressLog.Length > 0)
                    ServiceAddressLog += "," + uri;
                else
                    ServiceAddressLog += uri;

            ConnectLog.WriteLog(uri, ServiceAddressLog, userName);


            //Load data ready
            tbl_RoleRight_Controller.Instance().LoadRoleRight();

            return true;
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            bool isValid = false;
            FormGlobals.App_ProgressShow(delegate()
            {
                isValid = CheckValid();
            }, "Xác minh tên đăng nhập và mật khẩu ...");

            if (isValid)
            {
                _dlgResult = DialogResult.OK;
                this.Close();
            }
            else
                txtUserPassword.Focus();
        }

    }
}
